package cn.com.wxd.action.component.tencent;

import java.io.IOException;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

import cn.com.wxd.biz.user.UsersService;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.util.RequestUtil;
import cn.com.wxd.util.action.AccessLogUtil;
import cn.com.wxd.common.security.PasswordUtil;
import cn.com.wxd.util.user.AccountType;
import cn.com.wxd.util.user.UserCoreUtil;

/**
 * Title:腾讯QQ登录处理
 * Description:腾讯qq登录处理控制
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created by ComXu on 2017/5/19.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
public class TencentLoginCtl {

    @Resource
    private UsersService usersService;

    private static final Logger log = LoggerFactory.getLogger(TencentLoginCtl.class);

    /**
     * 请求腾讯QQ登录
     *
     * @return
     */
    @RequestMapping("/tencentLogin")
    public void tencentLogin(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        try {
            HttpSession session = request.getSession();
            String lasturl = request.getParameter("lasturl");
            session.setAttribute("QQLOGIN-LASTURL", lasturl);
            request.removeAttribute("lasturl");
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException | IOException e) {
            log.error("QQ登录连接错误" + e.getMessage());
        }
    }

    /**
     * 腾讯登录返回信息处理
     *
     * @return
     */
    @RequestMapping("/tencentLoginRedirect")
    public String tencentLoginRedirect(HttpServletRequest request) {
        HashMap<String, Object> param = new HashMap<>();
        UsersInfo users = null;
        AccountInfo accountInfo = null;
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken;
            String openID = null;
            UserInfoBean userInfoBean = null;
            String headSrc;
            long tokenExpireIn;
            if (accessTokenObj.getAccessToken().equals("")) {
                log.warn("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();
                request.getSession().setAttribute("qq_access_token", accessToken);
                request.getSession().setAttribute("qq_token_expirein", String.valueOf(tokenExpireIn));
                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();

                //设置账户信息
                users = new UsersInfo();
                accountInfo = new AccountInfo();
                accountInfo.setUserName(openID); //账号
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                userInfoBean = qzoneUserInfo.getUserInfo();
                if (userInfoBean.getRet() == 0) {
                    users.setNickName(userInfoBean.getNickname());  //昵称
                    param.put("nickName", users.getNickName());
                    users.setSex(userInfoBean.getGender());
                    param.put("sex", users.getSex());
                    param.put("headImg", users.getHeadImg());
                } else {
                    return "";
                }
            }
            String ip = RequestUtil.getRemortIP(request);
            accountInfo.setLalogIp(ip);
            //param.put("lastLoginIp",ip);
            String time = DateUtil.getDatetimeStr();
            accountInfo.setLalogTime(time);
            //param.put("lalogTime",time);
            if (!usersService.queryUserB(openID)) {
                users.setCreateTime(time);
                users.setUserType("ordinary");
                users.setIsDisabled("N");
                users.setPassWord(PasswordUtil.encrypeBase64(openID));

                accountInfo.setCreateTime(time);
                accountInfo.setType(AccountType.QQ);

                accountInfo.setUsersInfo(users);

                if (!usersService.addUser(accountInfo))       //注册新的用户
                {
                    return "";
                }
            } else {
                if (!usersService.updateBaseUserInfo(accountInfo.getUserName(), param)
                        || !usersService.updateLoginInfo(accountInfo.getUserName(), ip))    //更新最新的用户基本信息
                {
                    log.warn("用户信息更新失败!");
                }
            }

            accountInfo = usersService.queryAccount(accountInfo.getUserName());   //从数据库获取用户

            UserCoreUtil.setLoginUser(request, accountInfo);
            UsersInfo loglast = accountInfo.getUsersInfo();
            if (loglast != null || loglast.getHeadImg() == null || loglast.getHeadImg().trim()
                    .equals("")) {  //如果用户没有本站头像
                if (userInfoBean != null) {
                    headSrc = userInfoBean.getAvatar().getAvatarURL100();   //获取用户100*100大小的空间头像
                    loglast.setHeadImg(headSrc);   //设置用户的空间头像为默认头像
                }
            }
            AccessLogUtil.addUserOperationLog(request, "QQLOGIN");
            //加入到日志中
            log.debug("腾讯QQ账号" + users.getNickName() + "上线了！");
        } catch (QQConnectException e) {
            log.error("无法连接到QQ登录平台" + e.getMessage());
            return "";

        }
        //获取登录前的页面。
        String lasturl = (String) request.getSession().getAttribute("QQLOGIN-LASTURL");
        if (lasturl != null && !lasturl.equals("")) {
            return "redirect:" + lasturl;  //转发到页面
        }
        return "";
    }
}
